package;
import php.FileSystem;
import php.io.File;
import php.Lib;
import php.Sys;

/**
 * ...
 * @author liwei
 */

class KV 
{
	private static var instance:KV;
	private var path:String = "temp/";
	public function new() 
	{
		if (instance == null) {
			instance = this;
		}else {
			throw "use KV.getInstance()";
		}
	}
	public static function getInstance():KV {
		if (instance == null) {
			instance = new KV();
		}
		return instance;
	}
	public function get(file:String,?unserialize:Bool=false):Dynamic {
		if (FileSystem.exists(path + file)) {
			var data:String = File.getContent(path + file);
			if (unserialize) {
				return Lib.unserialize(data);
			}
			return data;
		}else {
			return "";
		}
	}
	public function set(file:String, data:Dynamic):Void {
		var content:String;
		if (Std.is(data, String)) {
			content = cast(data, String);			
		}else{
			content = Lib.serialize(data);
		}
		File.saveContent(path + file, content);
	}
	public function delete(file:String):Void {
		if (FileSystem.exists(path + file)) {
			FileSystem.deleteFile(path + file);
		}
	}
}